package com.ccm.demo.springbootsecurity.security;

import com.ccm.demo.springbootsecurity.dao.SysRoleMapper;
import com.ccm.demo.springbootsecurity.dao.SysUserMapper;
import com.ccm.demo.springbootsecurity.entity.SysRole;
import com.ccm.demo.springbootsecurity.entity.SysUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private SysRoleMapper sysRoleMapper;

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		SysUser sysUser = sysUserMapper.selectByUsername(s);
		if (sysUser == null) {
			throw new UsernameNotFoundException("用户名错误");
		}
		List<SysRole> roles = sysRoleMapper.selectByUserId(sysUser.getSysId());
		List<SimpleGrantedAuthority> authorities = new ArrayList<>(roles.size());
		for (SysRole sysRole : roles) {
			authorities.add(new SimpleGrantedAuthority(sysRole.getRoleName()));
		}
		boolean enable;
		if (sysUser.getEnabled()==1){
			enable=true;
		}else{
			enable=false;
		}
		return new User(sysUser.getSysUsername(),sysUser.getSysPassword(),enable,true,true,true,authorities);
	}
}
